package com.hainiu.cat.interview.nio;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * copy的整个过程：                                          channel.read()               channel.write()
 * 文件（file)----->输入流的通道 inputStream.getChannel()  -------------------> 缓冲区   ---------------------> 输出流的通道------> 文件
 */
public class NIOFileChannel {

    private ByteBuffer byteBuffer ;

    public static void main(String[] args) throws Exception{
//        writeFile();
//        readFile();
//        copyFile();

    }

    private static void copyFile() throws IOException {
        File file = new File("biji.txt");
        File targetFile = new File("biji1.txt");

        FileInputStream inputStream = new FileInputStream(file);

        FileChannel channel = inputStream.getChannel();

        FileOutputStream outputStream = new FileOutputStream(targetFile);
        FileChannel outChannel = outputStream.getChannel();

        // 此处若指定了等于文件大小 则会一次就被读取完毕，即channel.read(byteBuffer)只需要执行一次
        ByteBuffer byteBuffer  = ByteBuffer.allocate(10);

        while (true) {
            // 将channel 中的数据读到缓冲区
            int read = channel.read(byteBuffer);

            if (read == -1) {
                break;
            }

            byteBuffer.flip();
            // 把缓冲区数据写道通道中
            outChannel.write(byteBuffer);

            // 复位  此处一定要记得clear 因为当读取后再反转-再去读取时 返回的read始终为0 不是-1
            byteBuffer.clear();
        }
        inputStream.close();
        outChannel.close();
    }

    private static void readFile() throws IOException {
        File file = new File("D:\\fileChannel.txt");
        FileInputStream inputStream = new FileInputStream(file);
        FileChannel channel = inputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(Math.toIntExact(file.length()));

        // 将数据读取到buffer中
        channel.read(byteBuffer);

        // byteBuffer.array()获取里面的字节
        System.out.println(new String(byteBuffer.array()));

        inputStream.close();
    }

    private static void writeFile() throws IOException {
        String str = "HI ! we are you";
        FileOutputStream outputStream = new FileOutputStream("D:\\fileChannel.txt");

        FileChannel channel = outputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        byteBuffer.put(str.getBytes());

        // 读写切换
        byteBuffer.flip();

        // 将缓冲数据存到通道
        channel.write(byteBuffer);

        outputStream.close();
    }
}
